﻿using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Repository;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WinForm_Mes.ProductManagement.BaseSetting;
using static WinForm_Mes.ProductManagement.BaseSet;

namespace WinForm_Mes.ProductManagement
{
    public partial class ProductTypeForm : DevExpress.XtraEditors.XtraForm
    {
        private string baseUrl = "http://localhost:5164";
        private HttpClient httpClient;
        public ProductTypeForm()
        {
            InitializeComponent();
            this.Text = "型号";
            httpClient = new HttpClient();
            InitializeEvents();
        }
        // 绑定按钮事件
        private void InitializeEvents()
        {
            //查询按钮点击事件
            simpleButton1.Click += SearchButton;
            // 重置按钮点击事件
            simpleButton2.Click += ResetButton;
            // 添加按钮点击事件
            simpleButton3.Click += AddButton;
            // 删除按钮点击事件
            simpleButton4.Click += DeleteButton;
            
        }
        private void TypeModel(object sender, EventArgs e)
        {
            LoadModelData();
        }
        // 加载型号数据
        private async void LoadModelData()
        {
            try
            {
                // 显示提示信息
                gridControl1.DataSource = null;
                // 调用后端API获取数据
                HttpResponseMessage response = await httpClient.GetAsync(baseUrl + "/api/Type/GetAllType");
                if (response.IsSuccessStatusCode)
                {
                    string jsonContent = await response.Content.ReadAsStringAsync();
                    var apiResponse = JsonConvert.DeserializeObject<ApiResponse<TypeModels>>(jsonContent);
                    var models = apiResponse.Items;
                    // 绑定数据到表格
                    gridControl1.DataSource = models;

                    // 设置列映射
                    gridView1.Columns["Id"].Visible = false;
                    gridView1.Columns["TypeCode"].Caption = "型号编号";
                    gridView1.Columns["TypeName"].Caption = "型号名称";
                }
                else
                {
                    MessageBox.Show("获取型号数据失败！");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("发生错误：" + ex.Message);
            }
        }
        //查询数据
        private async void SearchButton(object sender, EventArgs e)
        {
            try
            {
                string TypeCode = textEdit1.Text.Trim();
                // 构建查询参数
                string queryParams = "?";
                if (!string.IsNullOrEmpty(TypeCode))
                {
                    queryParams += $"TypeCode={TypeCode}&";
                }
                // 去掉最后一个 & 号
                if (queryParams.EndsWith("&"))
                {
                    queryParams = queryParams.Substring(0, queryParams.Length - 1);
                }
                // 如果只有问号则不附加参数
                if (queryParams == "?")
                {
                    queryParams = "";
                }

                HttpResponseMessage response = await httpClient.GetAsync(baseUrl + "/api/Type/GetAllType" + queryParams);
                if (response.IsSuccessStatusCode)
                {
                    string jsonContent = await response.Content.ReadAsStringAsync();
                    var apiResponse = JsonConvert.DeserializeObject<ApiResponse<TypeModels>>(jsonContent);
                    var types = apiResponse.Items;
                    // 绑定数据到表格
                    gridControl1.DataSource = types;
                }
                else
                {
                    MessageBox.Show("查询型号编号数据失败！");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("查询发生错误：" + ex.Message);
            }
        }
        // 重置数据
        private void ResetButton(object sender, EventArgs e)
        {
            textEdit1.Text = "";
            LoadModelData();
        }

        private async void AddButton(object sender, EventArgs e)
        {
            using (var addTypeForm = new AddTypeForm())
            {
                if(addTypeForm.ShowDialog() == DialogResult.OK)
                {
                    LoadModelData();
                };
            }
        }

        // 删除单个型号
        // 批量删除按钮点击事件
        private async void DeleteButton(object sender, EventArgs e)
        {
            // 获取选中行
            int[] selectedRows = gridView1.GetSelectedRows();
            if (selectedRows.Length == 0)
            {
                MessageBox.Show("请选择要删除的记录！");
                return;
            }

            // 确认删除
            if (MessageBox.Show($"确定要删除选中的 {selectedRows.Length} 条记录吗？", "确认删除",
                MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
            {
                return;
            }

            try
            {
                List<long> ids = new List<long>();
                foreach (int rowHandle in selectedRows)
                {
                    ids.Add(Convert.ToInt64(gridView1.GetRowCellValue(rowHandle, "Id")));
                }

                // 发送批量删除请求
                var content = new StringContent(
                    JsonConvert.SerializeObject(ids),
                    Encoding.UTF8,
                    "application/json");

                HttpResponseMessage response = await httpClient.PostAsync(baseUrl + "/api/Type/DelType", content);

                if (response.IsSuccessStatusCode)
                {
                    MessageBox.Show("删除成功！");
                    LoadModelData();
                }
                else
                {
                    MessageBox.Show("删除失败！");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("删除发生错误：" + ex.Message);
            }
        }
        // 删除单个型号
        private async void DeleteModel(long Id)
        {
            // 获取选中行
            int[] selectedRows = gridView1.GetSelectedRows();
            if (selectedRows.Length == 0)
            {
                MessageBox.Show("请选择要删除的记录！");
                return;
            }
            if (MessageBox.Show("确定要删除此记录吗？", "确认删除",
                MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
            {
                return;
            }

            try
            {
                HttpResponseMessage response = await httpClient.DeleteAsync($"{baseUrl}/api/Type/DelType/{Id}");

                if (response.IsSuccessStatusCode)
                {
                    MessageBox.Show("删除成功！");
                    LoadModelData();
                }
                else
                {
                    MessageBox.Show("删除失败！");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("删除发生错误：" + ex.Message);
            }
        }
        // 型号数据模型
        public class TypeModels
        {
            /// <summary>
            /// 主键Id
            /// </summary>
            public long Id { get; set; }
            /// <summary>
            /// 型号编码
            /// </summary>
            public string TypeCode { get; set; }
            /// <summary>
            /// 型号名称
            /// </summary>
            public string TypeName { get; set; }
        }

        // API响应包装类
        public class ApiResponse<T>
        {
            public int Total { get; set; } = 0;
            public int Index { get; set; } = 1;
            public int Size { get; set; } = 10;
            public List<T> Items { get; set; } = new List<T>();
        }
    }
}